package com.engr.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.engr.model.User;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @program: train-shiro
 * @desc: 控制账号同时登录人数限制
 * @author: lyx
 * @date: 2018-11-11 11:07
 **/
public class KickoutFilter extends AccessControlFilter {

    private Cache<String, Deque<Serializable>> cache;
    /**
     * 同一个帐号最大会话数 默认5
     */
    private int maxSession = 5;

    /**
     * 踢出后到的地址
     */
    private String kickoutUrl;
    /**
     * 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
     */
    private boolean kickoutAfter = false;

    private SessionManager sessionManager;


    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("shiro_redis_cache");
    }

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request,response);

        if(!subject.isAuthenticated() && !subject.isRemembered()){
            // 如果没有登录,直接进行后面的流程
            return true;
        }
        Session session = subject.getSession();
        User user = (User) subject.getPreviousPrincipals();
        String username = user.getUsername();
        Serializable sessionId = session.getId();
        // 读取缓存,没有就存入
        Deque<Serializable> deque = cache.get(username);
        // 如果此用户没有session队列,就证明此用户没有登录过,缓存中没有,就new一个队列,不然deque对象为空,会有nullPointException
        if (deque == null) {
            deque = new LinkedList<>();
        }
        //如果队列里面没有此sessionid,且用户没有被踢出,放入队列
        if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
            // 将sessioId放入队列
            deque.push(sessionId);
            // 将用户的sessionId缓存
            cache.put(username,deque);
        }
        // 当队列里面的sessionId超出最大队列数,开始踢人
        while (deque.size() > maxSession) {
            Serializable kickoutSessionId = null;
            // 如果踢出后者
            if(kickoutAfter){
                kickoutSessionId = deque.removeFirst();
                cache.put(username, deque);
            }else{
                // 如果踢出前者
                kickoutSessionId = deque.removeLast();
                // 更新缓存队列
                cache.put(username, deque);
            }
            // 获取被踢出的缓存对象
            Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
            if (kickoutSession != null) {// 表示设置会话的kickoutsession被踢除了
                kickoutSession.setAttribute("kickout", true);
            }
        }
        // 如果被路踢除了,直接退出,重定向到踢出后的地址
        if (session.getAttribute("kickout") != null && (Boolean) session.getAttribute("kickout")==true) {
            // 会话被踢出了,退出登录
            subject.logout();
            saveRequest(request);

            Map<String, String> resultMap = new HashMap<>(2);
            //判断是不是ajax请求
            if("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))){
                resultMap.put("user_status", "300");
                resultMap.put("message", "您已在其它地方登录,请重新登录");
                // 输出json串
                out(response, resultMap);
            }else{
                // 重定向
                WebUtils.issueRedirect(request, response,kickoutUrl);
            }

        }


        return false;
    }

    private void out(ServletResponse response,Map<String,String> map){

        PrintWriter printWriter = null;
        try {
            response.setCharacterEncoding("utf-8");
            printWriter = response.getWriter();
            printWriter.println(JSON.toJSONString(map));
            printWriter.flush();
        } catch (Exception e){
            System.out.println("输出异常");
        } finally {
            if(printWriter!=null){
                printWriter.close();
            }
        }
    }
}
